<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item label="编码" prop="questionCode">
        <el-input v-model="queryParams.questionCode" placeholder="请输入编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="题目类型" prop="questionType">
        <el-select v-model="queryParams.questionType" placeholder="请选择题目类型" clearable style="width: 215px">
          <el-option v-for="(dict, index) in dict.type.topic_type" :key="index" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="难易程度" prop="questionEasy">
        <el-select v-model="queryParams.questionEasy" placeholder="请选择题目类型" clearable style="width: 215px">
          <el-option v-for="(dict, index) in dict.type.difficulty" :key="index" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="重要性" prop="questionGrade">
        <el-select v-model="queryParams.questionGrade" placeholder="重要性" clearable style="width: 215px">
          <el-option v-for="(dict, index) in dict.type.grade" :key="index" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['juan:juanQuestion:add']" type="primary" plain icon="el-icon-plus" size="mini" :disabled="treeType !== 'knowledge'" @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['juan:juanQuestion:edit']"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['juan:juanQuestion:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button  :disabled="treeType!='course'" v-hasPermi="['juan:juanQuestion:export']" type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button  :disabled="treeType!='course'" v-hasPermi="['juan:juanQuestion:export']" type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="juanQuestionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编码" align="center" prop="questionCode" />
      <el-table-column label="题目类型" align="center" prop="questionType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.topic_type" :value="scope.row.questionType" />
        </template>
      </el-table-column>
      <el-table-column label="难度系数" align="center" prop="questionDifficult">
        <template slot-scope="scope">
          {{ scope.row.questionDifficult | floatFormat }}
        </template>
      </el-table-column>
      <el-table-column label="难易程度" align="center" prop="questionEasy">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.difficulty" :value="scope.row.questionEasy" />
        </template>
      </el-table-column>
      <el-table-column label="重要性" align="center" prop="questionGrade">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.grade" :value="scope.row.questionGrade" />
        </template>
      </el-table-column>
      <el-table-column label="能力层次" align="center" prop="capabilityLevel">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.capability_level" :value="scope.row.capabilityLevel" />
        </template>
      </el-table-column>
      <el-table-column label="分值" align="center" prop="score" />
      <el-table-column label="相关性" align="center" prop="relevance" />
      <el-table-column label="考核内容" align="center" prop="examine" />
      <el-table-column label="题目内容" align="center" prop="questionContent" min-width="80">
        <template slot-scope="scope">
          <el-button slot="reference" size="small" @click="showHtml(scope.row.questionContent)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="答案" align="center" prop="answer" min-width="80">
        <template slot-scope="scope">
          <el-button slot="reference" size="small" @click="showHtml(scope.row.answer)">查看</el-button>
        </template>
      </el-table-column>
      <!--      <el-table-column label="创建人" align="center" prop="createdBy" />-->
<!--      <el-table-column label="创建时间" align="center" prop="createdTime" width="180">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.createdTime, "{y}-{m}-{d}") }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="操作" fixed="right" width="120" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-hasPermi="['juan:juanQuestion:edit']" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            v-hasPermi="['juan:juanQuestion:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改题目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!--        <el-form-item label="课程ID" prop="courseId">-->
        <!--          <el-input v-model="form.courseId" placeholder="请输入课程ID" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="章节ID" prop="chapterId">-->
        <!--          <el-input v-model="form.chapterId" placeholder="请输入章节ID" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="知识点ID" prop="knowledgeId">-->
        <!--          <el-input v-model="form.knowledgeId" placeholder="请输入知识点ID" />-->
        <!--        </el-form-item>-->

        <el-row :gutter="20">
<!--          <el-col :span="8">-->
<!--            <el-form-item label="编码" prop="questionCode">-->
<!--              <el-input v-model="form.questionCode" maxlength="20" style="width: 200px" placeholder="请输入编码" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="8">
            <el-form-item label="题目类型" prop="questionType">
              <el-select v-model="form.questionType" placeholder="请选择题目类型" clearable style="width: 200px">
                <el-option v-for="(dict, index) in dict.type.topic_type" :key="index" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="重要性" prop="questionGrade">
              <el-select v-model="form.questionGrade" placeholder="请选择重要性" clearable style="width: 200px">
                <el-option v-for="(dict, index) in dict.type.grade" :key="index" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="难易程度" prop="questionEasy">
              <el-select v-model="form.questionEasy" placeholder="请选择难易程度" clearable style="width: 200px">
                <el-option v-for="(dict, index) in dict.type.difficulty" :key="index" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="难度系数" prop="questionDifficult">
              <el-input-number
                v-model="form.questionDifficult"
                :precision="2"
                :min="0"
                :max="1"
                :step="0.1"
                style="width: 120px"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="能力层次" prop="capabilityLevel">
              <el-select v-model="form.capabilityLevel" placeholder="请选择能力层次" clearable>
                <el-option v-for="(dict, index) in dict.type.capability_level" :key="index" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="分值" prop="score">
              <el-input-number v-model="form.score" :precision="0" :min="0" :max="100" :step="1" style="width: 120px" />
              <span>分</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="相关性" prop="relevance">
              <el-input v-model="form.relevance" maxlength="20" style="width: 200px" placeholder="请输入相关性" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="考核内容" prop="examine">
              <el-input v-model="form.examine" maxlength="20" style="width: 200px" placeholder="请输入考核内容" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-form-item label="题干" prop="questionSubject">
          <TinymceEditor v-if="open" v-model="form.questionSubject" :height="400" />
        </el-form-item> -->
        <el-form-item label="选项内容">
          <TinymceEditor v-if="open" v-model="form.questionContent" :height="400" />
        </el-form-item>
        <el-form-item label="答案">
          <TinymceEditor v-if="open" v-model="form.answer" :height="300" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        :data="uploadData"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip text-center">
          <span>仅允许导入xls、xlsx格式文件。</span>
<!--          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate"-->
<!--            >下载模板</el-link-->
<!--          >-->
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"  href="http://127.0.0.1:8075/static/public/timutemplate.xlsx"
          >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getQuestionList, getJuanQuestion, delJuanQuestion, addJuanQuestion, updateJuanQuestion } from "@/api/juan/juanQuestion";
import TinymceEditor from "@/components/TinymceEditor";
import { getToken } from "@/utils/auth";

export default {
  name: "JuanQuestion",
  components: { TinymceEditor },
  dicts: ["topic_type", "difficulty", "grade", "capability_level"],
  props: {
    autoLoad: {
      type: Boolean,
      default: true,
    },
    reposId: {
      type: String,
      default: "",
    },
    knowledgeId: {
      type: String,
      default: "",
    },
    courseId: {
      type: String,
      default: "",
    },
    treeType: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      //上传携带参数
      uploadData:{},
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题目表格数据
      juanQuestionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken()
        },
        // 上传的地址
        url: "http://127.0.0.1:8075/juan/juanQuestion/importQuestions",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // courseId: undefined,
        // chapterId: undefined,
        // knowledgeId: undefined,
        questionCode: undefined,
        questionType: undefined,
        questionDifficult: undefined,
        questionEasy: undefined,
        capabilityLevel: undefined,
        questionMajor: undefined,
        questionGrade: undefined,
        questionSubject: undefined,
        questionContent: undefined,
        createdBy: undefined,
        createdTime: undefined,
        updatedBy: undefined,
        updatedTime: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // questionId: [
        //   { required: true, message: "ID不能为空", trigger: "blur" }
        // ],
        // courseId: [
        //   { required: true, message: "课程ID不能为空", trigger: "blur" }
        // ],
        // chapterId: [
        //   { required: true, message: "章节ID不能为空", trigger: "blur" }
        // ],
        // knowledgeId: [
        //   { required: true, message: "知识点ID不能为空", trigger: "blur" }
        // ],
        // questionCode: [{ required: true, message: "编码不能为空", trigger: "blur" }],
        questionType: [{ required: true, message: "题目类型不能为空", trigger: "change" }],
        questionDifficult: [{ required: true, message: "难度系数不能为空", trigger: "blur" }],
        questionEasy: [{ required: true, message: "难易程度不能为空", trigger: "blur" }],
        capabilityLevel: [{ required: true, message: "能力层次不能为空", trigger: "blur" }],
        score: [{ required: true, message: "分值不能为空", trigger: "blur" }],
        questionMajor: [{ required: true, message: "专业不能为空", trigger: "blur" }],
        questionGrade: [{ required: true, message: "重要性不能为空", trigger: "blur" }],
        questionSubject: [{ required: true, message: "题干不能为空", trigger: "blur" }],
        questionContent: [{ required: true, message: "选项内容不能为空", trigger: "blur" }],
        createdBy: [{ required: true, message: "创建人不能为空", trigger: "blur" }],
        createdTime: [{ required: true, message: "创建时间不能为空", trigger: "blur" }],
        updatedBy: [{ required: true, message: "更新人不能为空", trigger: "blur" }],
        updatedTime: [{ required: true, message: "更新时间不能为空", trigger: "blur" }],
      },
    };
  },
  created() {
    if (this.autoLoad) {
      this.getList();
    }
  },
  methods: {
    /** 查询题目列表 */
    getList() {
      this.loading = true;
      let options = {
        ...this.queryParams,
        reposId: this.reposId,
        knowledgeId: this.knowledgeId,
        treeType: this.treeType,
      };
      getQuestionList(options)
        .then((response) => {
          this.juanQuestionList = response.data.rows;
          this.total = response.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        questionId: undefined,
        courseId: undefined,
        chapterId: undefined,
        knowledgeId: undefined,
        questionCode: undefined,
        questionType: undefined,
        questionDifficult: undefined,
        questionEasy: undefined,
        questionMajor: undefined,
        questionGrade: undefined,
        questionSubject: undefined,
        questionContent: undefined,
        createdBy: undefined,
        createdTime: undefined,
        updatedBy: undefined,
        updatedTime: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.questionId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      // if (!this.reposId) {
      //   this.$modal.msgWarning("请选择题库");
      //   return;
      // }
      if (!this.knowledgeId) {
        this.$modal.msgWarning("请选择知识点");
        return;
      }
      this.reset();
      this.open = true;
      this.title = "添加题目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log(this.dict);
      this.loading = true;
      this.reset();
      const questionId = row.questionId || this.ids;
      getJuanQuestion(questionId).then((response) => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改题目";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;

          let options = {
            ...this.form,
          };

          // if (!options.reposId) {
          //   options.reposId = this.reposId;
          // }
          if (!options.courseId) {
            options.courseId = this.courseId;
          }
          if (!options.knowledgeId) {
            options.knowledgeId = this.knowledgeId;
          }
          if (!options.treeType) {
            options.treeType = this.treeType;
          }

          if (options.questionId != null) {
            updateJuanQuestion(options)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addJuanQuestion(options)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const questionIds = row.questionId || this.ids;
      this.$modal
        .confirm("是否确认删除题目？")
        .then(() => {
          this.loading = true;
          return delJuanQuestion(questionIds);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {})
        .finally(() => {
          this.loading = false;
        });
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download("/juan/juanQuestion/importTemplate", {}, `template_${new Date().getTime()}.xlsx`);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.uploadData.couserId = this.courseId
      this.uploadData.knowledgeId = this.knowledgeId
      this.$refs.upload.submit();
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "题目导入";
      this.upload.open = true;
    },
    /** 导出按钮操作 */
    handleExport() {
      // if (!this.reposId) {
      //   this.$modal.msgWarning("请选择题库");
      //   return;
      // }
      // if (!this.knowledgeId) {
      //   this.$modal.msgWarning("请选择知识点");
      //   return;
      // }
      this.download(
        "juan/juanQuestion/export",
        {
          ...this.queryParams,
          reposId: this.reposId,
          courseId: this.courseId,
          // knowledgeId: this.knowledgeId,
        },
        `题目列表 ${new Date().toLocaleString()}.xlsx`
      );
    },
    showHtml(html) {
      this.$alert(html, "题目信息", {
        dangerouslyUseHTMLString: true,
        customClass: "question-html",
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  padding: 0 6px 0 20px;

  .pagination-container {
    margin-bottom: 0;
  }
}
</style>
<style lang="scss">
.question-html {
  width: 1000px;
  .el-message-box__content {
    box-sizing: border-box;
    word-wrap: break-word;
  }
}
</style>
